﻿using ENode.Commanding;
using ENode.Infrastructure;
using ESTAR.Commands.Auth;
using ESTAR.Domain.Auth;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace ESTAR.CommandHandlers.Auth
{
    public class UserInfoCommandHandler :
        ICommandHandler<RegisterNewUserInfoCommand>
    {
        private readonly ILockService _lockService;
        private readonly RegisterUserInfoService _registerUserInfoService;

        public UserInfoCommandHandler(ILockService lockService, RegisterUserInfoService registerUserInfoService)
        {
            _lockService = lockService;
            _registerUserInfoService = registerUserInfoService;
        }

        public Task HandleAsync(ICommandContext context, RegisterNewUserInfoCommand command)
        {
            return _lockService.ExecuteInLock(typeof(UserInfo).Name, () =>
            {
                return Task.Factory.StartNew(() =>
                {
                    var account = new UserInfo(command.AggregateRootId, command.UserName, command.Password);
                    _registerUserInfoService.RegisterAccount(account);
                    context.Add(account);
                });
            });
        }
    }

}